package com.baseLearn.learn.arithmetic;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * Least Recently Used 最近最少使用
 */
public class LRULinkedHashMap<K, V> extends LinkedHashMap<K, V> {

    private final int maxCapacity;//最大容量

    private static final float DEFAULT_LOAD_FACTOR = 0.75f;//加载因子

    private final Lock lock = new ReentrantLock(); //重入锁

    //初始化容量大小
    public LRULinkedHashMap(int maxCapacity) {

        //设置linkedHashMap参数,true代表有序排列
        super(maxCapacity, DEFAULT_LOAD_FACTOR, true);
        this.maxCapacity = maxCapacity;
    }

    @Override
    public boolean removeEldestEntry(Map.Entry<K, V> eldest) {
        return size() > maxCapacity;
    }

    @Override
    public boolean containsKey(Object key) {
        try {
            lock.lock();
            return super.containsKey(key);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public V put(K key, V value) {
        try {
            lock.lock();
            return super.put(key, value);
        } finally {
            lock.unlock();
        }

    }

    public static void main(String[] args) {
        LRULinkedHashMap<String, String> lru = new LRULinkedHashMap<>(3);
        lru.put("1", "1");
        lru.put("2", "2");
        lru.put("3", "3");
        lru.put("4", "4");
        System.out.println("lru---size=" + lru.size());
        for (String map : lru.keySet()) {
            System.out.println("1.初始key==" + map);
        }
        lru.put("5", "5");
        for (String map : lru.keySet()) {
            System.out.println("2.数据key==" + map);
        }

        System.out.println("利用key=3" + lru.get("3"));
        for (String map : lru.keySet()) {
            System.out.println("3.数据key==" + map);
        }

        lru.put("6", "6");
        for (String map : lru.keySet()) {
            System.out.println("4.数据key==" + map);
        }
    }

}
